package com.cy.controller.interceptor;

import cn.hutool.core.util.StrUtil;
import com.cy.common.Constant;
import com.cy.entity.LoginTicket;
import com.cy.entity.User;
import com.cy.service.LoginTicketService;
import com.cy.service.UserService;
import com.cy.util.CookieUtil;
import com.cy.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @Author: cy
 * @Date: 2022/01/02/16:08
 * @Description:   登录凭证拦截器
 */
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Resource
    private LoginTicketService loginTicketService;

    @Resource
    private UserService userService;

    @Resource
    private HostHolder hostHolder;


    //在controller之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie中获取凭证
        String ticket = CookieUtil.getValue(request, "ticket");
        if(StrUtil.isNotBlank(ticket)){
            // 查询凭证
            LoginTicket loginTicket = loginTicketService.findLoginTicket(ticket);

            // 检查凭证是否有效
            if(loginTicket != null && loginTicket.getStatus() == Constant.LOGIN_TICKET_CAN_USE && loginTicket.getExpired().after(new Date())){
                // 根据凭证查询用户
                User user = userService.findUserById(loginTicket.getUserId());
                // 在本次请求中持有用户
                hostHolder.setUser(user);

                // 构建用户认证的结果,并存入SecurityContext,以便于Security进行授权.
                Authentication authentication = new UsernamePasswordAuthenticationToken(
                        user, user.getPassword(), userService.getAuthorities(user.getId()));
                SecurityContextHolder.setContext(new SecurityContextImpl(authentication));

            }

        }
        return true;
    }


    //在controller之后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if(user != null && modelAndView != null){
            modelAndView.addObject("loginUser", user);
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
//        SecurityContextHolder.clearContext();
    }


}



